var time = require('../../../utils/util');
var BASE_URL = getApp().globalData.BASE_URL
var util = require('../../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    iflogin: true, //扫码进来是否登录
    dingdanid: '', //订单id
    detailid: '', //详情id
    uid: '', //被助力人id
    huodongdetail: '',
    imgurl: '',
    huodonglist: '',
    current_page: '', //上拉加载更多当前页
    last_page: '', //上拉加载更多最后页
    showflag: false, //控制上拉加载更多的出现和隐藏,
    showfinish: false, //控制没有数据的出现和隐藏
    helpsuccess: false,
    opid: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this
    console.log(options)
    if (options.src.length < 50 && options.src.length!==0) {
      this.setData({
        imgurl: `${BASE_URL}` + options.src,
      })
    } else {
      this.setData({
        imgurl: options.src,
      })
    }
    
    this.setData({
      dingdanid: options.dingdanid,
      detailid: options.detailid,
      uid: options.uid,
      opid: options.opid
    })
    if (time.iflogin()) {
      this.setData({
        iflogin: false
      })
    }
    wx.request({
      url: `${BASE_URL}/headline/list_data.html?page=1&size=6&zhi=%E6%B4%BB%E5%8A%A8&type=xiaochengxv`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json' //GET方式是这个
      },
      success(res) {
        console.log(res)
        res.data.list.forEach(function (item, index) {
          item.info=JSON.parse(item.info)
          if (item.other_info) {
            item.other_info = ''
          }
          var newDateTime = new Date().getTime()/1000
          item.shijian=util.formatTime(item.info.shijian)
          if( Math.floor(newDateTime)>item.shijian){
            item.falg=false
          }else{
            item.falg=true
          }
        })
        _this.setData({
          huodonglist: res.data.list,
          current_page:1,
          last_page: res.data.last_page,
        })
      }
    })
    wx.request({
      url: `${BASE_URL}/pay/index`,
      method: "POST",
      data: {
        id: _this.data.dingdanid,
        type: 'xiaochengxv',
        uid: _this.data.uid
      },
      header: {
        'Content-Type': 'application/json' //GET方式是这个
      },
      success(res) {
        console.log(res)
        res.data.list.time = time.formatTimeTwo(res.data.list.time, 'Y-M-D h:m:s');
        res.data.huodong.bannerimage = `${BASE_URL}` + res.data.huodong.bannerimage
        if (!_this.data.iflogin) {
          var openid = wx.getStorageSync('USER')
          if (res.data.list.is_paid == 1) {
            if (_this.data.opid == openid.xopenid) {
              wx.redirectTo({
                url: `/views/huodongdetail/helppage/index?id=${_this.data.dingdanid}&huodongid=${_this.data.detailid}`
              })
            } else {
              _this.setData({
                helpsuccess: true
              })
            }
          }
        } else {
          _this.setData({
            iflogin: true
          })
        }
        _this.setData({
          huodongdetail: res.data,
        })
      }
    })

  },
  getUserProfile: function () {
    var _this = this
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        wx.setStorage({
          key: "data",
          data: res.userInfo,
        })
        var openId = wx.getStorageSync('openid')
        var unionId = wx.getStorageSync('unionid')
        console.log(openId, unionId)
        _this.login(res.userInfo.avatarUrl, res.userInfo.city, res.userInfo.country, res.userInfo.gender, res.userInfo.language, res.userInfo.nickName, openId, res.userInfo.province, unionId)
      },
      fail: (res) => {
        wx.showToast({
          title: '取消登录,助力失败',
          icon: 'none',
        })
      }
    })

  },
  help: function () {
    console.log('已经登录然后为好友助力')
    var _this = this
    var userinfo = wx.getStorageSync("USER")
    wx.request({
      url: `${BASE_URL}/huodong/good`, //仅为示例，并非真实的接口地址
      data: {
        id: _this.data.dingdanid,
        uid: userinfo.id,
        huodongdetailid: _this.data.detailid
      },
      method: "POST",
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res)
        wx.showToast({
          title: res.data.error,
          icon: 'none',
          duration: 2000
        })
        if (res.data.status == 1) {
          _this.setData({
            iflogin: false,
            helpsuccess: true
          })
        }
      }
    })

  },

  gohuodong: function () {
    wx.reLaunch({
      url: `/views/index/activity/index`
    })
  },
  articleDetail: function (e) {
    var id = e.currentTarget.dataset.id
    wx.redirectTo({
      url: `/views/huodongdetail/index?id=${id}`
    })
  },

  login: function (avatarUrl, city, country, gender, language, nickName, openId, province, unionId) {
    var _this = this
    wx.request({
      url: `${BASE_URL}/ajax/wechatinfo`, //仅为示例，并非真实的接口地址
      data: {
        avatarUrl: avatarUrl,
        city: city,
        country: country,
        gender: gender,
        language: language,
        nickName: nickName,
        openId: openId,
        province: province,
        unionId: unionId,
      },
      method: "POST",
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res)
        if (res.data == '该账号未注册') {
          wx.showToast({
            title: '登录失败请重试',
            icon: 'error',
            duration: 2000
          })
        } else {
          wx.setStorage({
            key: "USER",
            data: res.data
          })
          console.log('留德diy登录', res.data.id)
          //  助力接口
          wx.request({
            url: `${BASE_URL}/huodong/good`, //仅为示例，并非真实的接口地址
            data: {
              id: _this.data.dingdanid,
              uid: res.data.id,
              huodongdetailid: _this.data.detailid
            },
            method: "POST",
            header: {
              'content-type': 'application/json' // 默认值
            },
            success(res) {
              console.log('没有登录给好友助力', res)
              wx.showToast({
                title: res.data.error,
                icon: 'none',
                duration: 2000
              })
              if (res.data.status == 1) {
                _this.setData({
                  helpsuccess: true
                })
              }
            }
          })
        }
      }
    })
  },

  //客服绑定
  handleContact(e) {},

  getcode: function () {
    wx.login({
      success: res => {
        wx.request({
          url: `${BASE_URL}/ajax/login`,
          data: {
            code: res.code
          },
          method: "GET",
          success: res => {
            // 获取到用户的 openid
            wx.setStorage({
              key: "openid",
              data: res.data.openid
            })
            wx.setStorage({
              key: "sessionkey",
              data: res.data.session_key
            })
            wx.setStorage({
              key: "unionid",
              data: res.data.unionid
            })
          }
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getcode()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: util.throttle(function () {
    var _this = this
    if (_this.data.current_page !== _this.data.last_page) {
      _this.setData({
        current_page: _this.data.current_page + 1,
        showflag: true,
        showfinish: false,
      })
    } else {
      _this.setData({
        showflag: false,
        showfinish: true,
      })
    }
    if (_this.data.showflag) {
      setTimeout(function () {
        wx.request({
          url: `${BASE_URL}/headline/list_data.html?page=${_this.data.current_page}&size=10&zhi=%E6%B4%BB%E5%8A%A8&type=xiaochengxv`,
          header: {
            'Content-Type': 'application/json', //GET方式是这个
          },
          method: "POST",
          success(res) {
            res.data.list.forEach(function (item, index) {
              item.info=JSON.parse(item.info)
              if (item.other_info) {
                item.other_info = ''
              }
              var newDateTime = new Date().getTime()/1000
              item.shijian=util.formatTime(item.info.shijian)
              if( Math.floor(newDateTime)>item.shijian){
                item.falg=false
              }else{
                item.falg=true
                _this.setData({
                  huodonglist: _this.data.huodonglist.concat(item),
                })
              }
            })
            _this.setData({
              showflag: false,
            })
          }
        })
      }, 500)
    }
  },
  2000),

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})